package com.hxb.example.controller;

import cn.hutool.core.util.StrUtil;
import com.hxb.example.entity.XxlJobGroup;
import com.hxb.example.entity.XxlJobInfo;
import com.hxb.example.model.ReturnT;
import com.hxb.example.service.XxlJobGroupService;
import com.hxb.example.service.XxlJobInfoService;
import com.hxb.example.service.XxlJobRegistryService;
import com.hxb.example.util.I18nUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * job group controller
 *
 * @author xuxueli 2016-10-02 20:52:56
 */
@Controller
@RequestMapping("/jobgroup")
public class JobGroupController {

    @Resource
    public XxlJobInfoService xxlJobInfoService;
    @Resource
    public XxlJobGroupService xxlJobGroupService;
    @Resource
    private XxlJobRegistryService xxlJobRegistryService;

    @RequestMapping
//	@PermissionLimit(adminuser = true)
    public String index(Model model) {
        return "jobgroup/jobgroup.index";
    }

    @RequestMapping("/pageList")
    @ResponseBody
//	@PermissionLimit(adminuser = true)
    public Map<String, Object> pageList(@RequestParam(required = false, defaultValue = "0") int start,
                                        @RequestParam(required = false, defaultValue = "10") int length,
                                        String appname, String title) {

        // page query
        Page<XxlJobGroup> page = xxlJobGroupService.page(Page.of(start / length + 1, length),
                QueryWrapper.create().like(XxlJobGroup::getAppname, appname, StrUtil.isNotBlank(appname))
                        .like(XxlJobGroup::getTitle, title, StrUtil.isNotBlank(title)));

        // package result
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("recordsTotal", page.getTotalRow());        // 总记录数
        maps.put("recordsFiltered", page.getTotalPage());    // 过滤后的总记录数
        maps.put("data", page.getRecords());                    // 分页列表
        return maps;
    }

    @RequestMapping("/save")
    @ResponseBody
//    @PermissionLimit(adminuser = true)
    public ReturnT<String> save(XxlJobGroup xxlJobGroup) {

        // valid
        if (StrUtil.isNotBlank(xxlJobGroup.getAppname())) {
            return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + "AppName"));
        }
        if (xxlJobGroup.getAppname().length() < 4 || xxlJobGroup.getAppname().length() > 64) {
            return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_appname_length"));
        }
        if (xxlJobGroup.getAppname().contains(">") || xxlJobGroup.getAppname().contains("<")) {
            return new ReturnT<String>(500, "AppName" + I18nUtil.getString("system_unvalid"));
        }
        if (StrUtil.isNotBlank(xxlJobGroup.getTitle())) {
            return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
        }
        if (xxlJobGroup.getTitle().contains(">") || xxlJobGroup.getTitle().contains("<")) {
            return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_title") + I18nUtil.getString("system_unvalid"));
        }
        // process
        xxlJobGroup.setUpdateTime(LocalDateTime.now());

        return xxlJobGroupService.save(xxlJobGroup) ? ReturnT.SUCCESS : ReturnT.FAIL;
    }

    @RequestMapping("/update")
    @ResponseBody
//    @PermissionLimit(adminuser = true)
    public ReturnT<String> update(XxlJobGroup xxlJobGroup) {
        // valid
        if (xxlJobGroup.getAppname() == null || xxlJobGroup.getAppname().trim().isEmpty()) {
            return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + "AppName"));
        }
        if (xxlJobGroup.getAppname().length() < 4 || xxlJobGroup.getAppname().length() > 64) {
            return new ReturnT<String>(500, I18nUtil.getString("jobgroup_field_appname_length"));
        }
        if (xxlJobGroup.getTitle() == null || xxlJobGroup.getTitle().trim().isEmpty()) {
            return new ReturnT<String>(500, (I18nUtil.getString("system_please_input") + I18nUtil.getString("jobgroup_field_title")));
        }
        // process
        xxlJobGroup.setUpdateTime(LocalDateTime.now());

        return xxlJobGroupService.updateById(xxlJobGroup) ? ReturnT.SUCCESS : ReturnT.FAIL;
    }

    @RequestMapping("/remove")
    @ResponseBody
//    @PermissionLimit(adminuser = true)
    public ReturnT<String> remove(int id) {

        // valid
        long count = xxlJobInfoService.count(QueryWrapper.create().eq(XxlJobInfo::getJobGroup, id)
                .eq(XxlJobInfo::getTriggerStatus, -1));
        if (count > 0) {
            return new ReturnT<String>(500, I18nUtil.getString("jobgroup_del_limit_0"));
        }

        List<XxlJobGroup> allList = xxlJobGroupService.list(QueryWrapper.create().or("t.app_name, t.title, t.id ASC"));
        if (allList.size() == 1) {
            return new ReturnT<String>(500, I18nUtil.getString("jobgroup_del_limit_1"));
        }

        return xxlJobGroupService.removeById(id) ? ReturnT.SUCCESS : ReturnT.FAIL;
    }

    @RequestMapping("/loadById")
    @ResponseBody
//    @PermissionLimit(adminuser = true)
    public ReturnT<XxlJobGroup> loadById(int id) {
        XxlJobGroup jobGroup = xxlJobGroupService.getById(id);
        return jobGroup != null ? new ReturnT<>(jobGroup) : new ReturnT<>(ReturnT.FAIL_CODE, null);
    }

}
